import 'dart:convert';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/models/assessment/assessmentDto.dart';
import 'package:ichinesereader/models/assessment/assessmentQueryDto.dart';
import 'package:ichinesereader/models/assessment/assessmentBookType.dart';
import 'package:ichinesereader/models/assessment/assessmentBooksResult.dart';
import 'package:ichinesereader/models/assessment/assessmentGradingDto.dart';
import 'package:ichinesereader/models/assessment/assessmentItem.dart';
import 'package:ichinesereader/models/assessment/assessmentQuestionsResult.dart';
import 'package:ichinesereader/models/assessment/assessmentRecordDto.dart';
import 'package:ichinesereader/models/assessment/assessmentRecordsResult.dart';
import 'package:ichinesereader/models/assessment/assessmentStudentQueryDto.dart';
import 'package:ichinesereader/models/assessment/assessmentStudentRecordsResult.dart';
import 'package:ichinesereader/models/assessment/questionRecordInfoResult.dart';
import 'package:ichinesereader/models/assessment/assessmentRecordsGradesResult.dart';
import 'package:ichinesereader/models/book/BookItem.dart';
import 'package:ichinesereader/models/common/StatusMessageResult.dart';
import 'package:ichinesereader/models/student/assessmentsResult.dart';
import 'package:ichinesereader/models/teacher/TeacherAssessment.dart';
import 'package:ichinesereader/models/teacher/TeacherAssessments.dart';
import 'package:ichinesereader/service/assessment.dart';
import 'package:ichinesereader/service/book.dart';
import 'package:ichinesereader/service/schooladmin.dart';
import 'package:ichinesereader/utils/StrUtil.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/utils/log.dart';
import '../exam/dto/assessment_question_record.body.dart';
import '../models/assessment/questionRecordSection.dart';
import '../models/book/bookAssigned.dart';
import '../models/knowledgeword/knowledgeDetailsResult.dart';

class AssessmentsController extends GetxController with StateMixin<dynamic> {
  AssessmentServiceProvider _assessmentServiceProvider =
      new AssessmentServiceProvider();
  SchoolAdminServiceProvider _schoolServiceProvider =
      new SchoolAdminServiceProvider();
  BookServiceProvider _bookServiceProvider = new BookServiceProvider();
  final box = Hive.box('appconfig');
  List<AssessmentItem> _assessItems = <AssessmentItem>[].obs;
  List<AssessmentItem> get assessItems => this._assessItems;
  List<AssessmentItem> _assessItemsForTeacher = <AssessmentItem>[].obs;
  List<AssessmentItem> get assessItemsForTeacher => this._assessItemsForTeacher;
  List<BookItem> _assessmentBenchmarkTests = <BookItem>[].obs;
  List<BookItem> get assessmentBenchmarkTests => this._assessmentBenchmarkTests;
  List<BookItem> _selectedAssessmentBenchmarkTests = <BookItem>[].obs;
  List<BookItem> get selectedAssessmentBenchmarkTests =>
      this._selectedAssessmentBenchmarkTests;

  List<BookItem> _assessmentBooks = <BookItem>[].obs;
  List<BookItem> get assessmentBooks => this._assessmentBooks;
  List<BookItem> _selectedAssessmentBooks = <BookItem>[].obs;
  List<BookItem> get selectedAssessmentBooks => this._selectedAssessmentBooks;

  List<QuestionRecord> _assessmentRecords = <QuestionRecord>[].obs;
  List<QuestionRecord> get assessmentRecords => this._assessmentRecords;

  List<QuestionRecord> _questionRecords = <QuestionRecord>[].obs;
  List<QuestionRecord> get questionRecords => this._questionRecords;

  Rx<AssessmentBookType> _currentAssessmentBookType =
      Rx<AssessmentBookType>(AssessmentBookType());
  Rx<AssessmentBookType> get currentAssessmentBookType =>
      this._currentAssessmentBookType;

  Rx<AssessmentQuestions> _assessmentQuestions =
      Rx<AssessmentQuestions>(AssessmentQuestions());
  Rx<AssessmentQuestions> get assessmentQuestions => this._assessmentQuestions;

  Rx<AssessmentQuestions> _assessmentRecordDetails =
      Rx<AssessmentQuestions>(AssessmentQuestions());
  Rx<AssessmentQuestions> get assessmentRecordDetails =>
      this._assessmentRecordDetails;

  Rx<QuestionRecordInfo> _assessmentQuestionRecordInfo =
      Rx<QuestionRecordInfo>(QuestionRecordInfo());
  Rx<QuestionRecordInfo> get assessmentQuestionRecordInfo =>
      this._assessmentQuestionRecordInfo;

  List<Map> writtenJson = [];
  List<Map> oralJson = [];
  List<Map> allJson = [];
  Rx<AssessmentRecordsGrades> _assessmentRecordsGrades =
      Rx<AssessmentRecordsGrades>(AssessmentRecordsGrades());
  Rx<AssessmentRecordsGrades> get assessmentRecordsGrades =>
      this._assessmentRecordsGrades;
  Rx<AssessmentStudentRecordsResult> _studentAssessmentRecord =
      Rx<AssessmentStudentRecordsResult>(AssessmentStudentRecordsResult());
  Rx<AssessmentStudentRecordsResult> get studentAssessmentRecord =>
      this._studentAssessmentRecord;

  QuestionRecordInfo? questionRecordInfo;
  List<TeacherAssessment> _assessAllItems = <TeacherAssessment>[].obs;
  List<TeacherAssessment> get assessAllItems => this._assessAllItems;
  List<QuestionRecordSection>? grammarRecordInfo;
  //List<QuestionRecordInfo>? questionRecordInfo;

  @override
  void onInit() {
    super.onInit();
  }

  Future<StatusMessageResult> createAssessment(
      AssessmentDto dto, String? assessmentId) async {
    var _statusMessageResult = StatusMessageResult();
    EasyLoading.show();
    try {
      var response =
          await _assessmentServiceProvider.createAssessment(dto, assessmentId);
      if (response.statusCode == 200) {
        _statusMessageResult.status = 1000;
        _statusMessageResult.message = 'Success';
      } else {
        _statusMessageResult.status = response.statusCode;
        _statusMessageResult.message = 'Failed';
      }
    } catch (e) {
      Log.debug(e);
      _statusMessageResult.status = 0;
      _statusMessageResult.message = 'Oops, something wrong ...'.tr;
    } finally {
      EasyLoading.dismiss();
    }
    return _statusMessageResult;
  }

  Future<StatusMessageResult> submitReportRecord(
      List<Map> records, String? bookCode) async {
    final box = Hive.box('appconfig');
    var username = box.get(CacheManagerKey['username'].toString());
    var profile =
        json.decode(box.get(CacheManagerKey['profilesettings'].toString()));
    String language = profile["language"];
    String lang = profile["lang"];
    var _statusMessageResult = StatusMessageResult();
    try {
      EasyLoading.show();
      var response = await _assessmentServiceProvider.postSubmitReportRecordNew(
          QuestionRecordBodyNew(
              userName: username,
              record: records,
              kind: 'WORD',
              audioType: lang,
              mode: 'Exercise',
              textType: language,
              type: 'LIBRARY',
              bookCode: bookCode));
      if (response.statusCode == 200) {
        _statusMessageResult = statusMessageResultFromJson(response.bodyString);
        // _statusMessageResult.status = 1000;
        // _statusMessageResult.message = 'Successfully submitted.';
      } else {
        _statusMessageResult.status = response.statusCode;
        _statusMessageResult.message = 'Failed to submit records.';
      }
    } catch (e) {
      Log.debug(e);
    } finally {
      EasyLoading.dismiss();
    }
    return _statusMessageResult;
  }

  Future<StatusMessageResult> submitAssessmentQuestionRecord(
      AssessmentRecordDto recorecordDto, String bookId) async {
    var _statusMessageResult = StatusMessageResult();
    try {
      EasyLoading.show();
      var response =
          await _assessmentServiceProvider.submitQuestionRecord(recorecordDto);
      if (response.statusCode == 200) {
        _statusMessageResult = statusMessageResultFromJson(response.bodyString);
        // _statusMessageResult.status = 1000;
        // _statusMessageResult.message = 'Successfully submitted.';
        // // _booksController.resetBookQuickReviewStatus(
        // //     bookId, json.decode(response.bodyString)['result']['id']);
      } else {
        _statusMessageResult.status = response.statusCode;
        _statusMessageResult.message = 'Failed to submit records.';
      }
    } catch (e) {
      Log.debug(e);
    } finally {
      EasyLoading.dismiss();
    }
    return _statusMessageResult;
  }

  Future<StatusMessageResult> saveAssessmentQuestionRecord(
      AssessmentRecordDto recorecordDto, String bookId) async {
    var _statusMessageResult = StatusMessageResult();
    try {
      EasyLoading.show();
      var response =
          await _assessmentServiceProvider.saveQuestionRecord(recorecordDto);
      if (response.statusCode == 200) {
        _statusMessageResult = statusMessageResultFromJson(response.bodyString);
        // _statusMessageResult.status = 1000;
        // _statusMessageResult.message = 'Successfully saved';
        // // _booksController.resetBookQuickReviewStatus(
        // //     bookId, json.decode(response.bodyString)['result']['id']);
      } else {
        _statusMessageResult.status = response.statusCode;
        _statusMessageResult.message = 'Failed to save records.';
      }
    } catch (e) {
      Log.debug(e);
    } finally {
      EasyLoading.dismiss();
    }
    return _statusMessageResult;
  }

  void refreshSelectedAssessmentBenchmarkTestbooks() {
    this._selectedAssessmentBenchmarkTests.clear();
    if (this._assessmentBenchmarkTests.isNotEmpty) {
      this._assessmentBenchmarkTests.forEach((element) {
        element.selected = false;
      });
    }
    change(this._assessmentBenchmarkTests, status: RxStatus.success());
  }

  void refreshSelectedAssessmentBooks() {
    this._selectedAssessmentBooks.clear();
    if (this._assessmentBooks.isNotEmpty) {
      this._assessmentBooks.forEach((element) {
        element.selected = false;
      });
    }
    change(this._assessmentBooks, status: RxStatus.success());
  }

  void fetchAssessmentQuestionsByAssessmentId(String assessmentId) async {
    try {
      var response = await _assessmentServiceProvider
          .getQuestionsByAssessmentId(assessmentId);
      if (response.statusCode == 200) {
        AssessmentQuestionsResult data = AssessmentQuestionsResult.fromJson(
            json.decode(response.bodyString));
        if (data.result != null)
          this._assessmentQuestions.value = data.result as AssessmentQuestions;
      }
    } catch (error) {
      Log.debug(error);
    }
  }

  void fetchQuestionGroupByBookCode(String bookCode) async {
    try {
      change(this._assessmentQuestionRecordInfo, status: RxStatus.loading());
      //var _language = box.get('UserLanguage') ?? 'Simplified';
      var response = await _assessmentServiceProvider
          .getQuestionGroupByBookCode(bookCode, true, true);
      if (response.statusCode == 200) {
        QuestionRecordInfoResult data =
            questionRecordInfoResultFromJson(response.bodyString);
        if (data.result != null)
          this._assessmentQuestionRecordInfo.value =
              data.result as QuestionRecordInfo;
        change(this._assessmentQuestionRecordInfo, status: RxStatus.success());
      }
    } catch (error) {
      change(null, status: RxStatus.error());
      Log.debug(error);
    }
  }

  void clearAssessmentQuestionRecordInfo() {
    this._assessmentQuestionRecordInfo.value = new QuestionRecordInfo();
  }

  void fetchAssessmentRecordInfoDetails(String recordId) async {
    try {
      EasyLoading.show();
      var response =
          await _assessmentServiceProvider.getAssessmentRecordDetails(recordId);
      if (response.statusCode == 200) {
        QuestionRecordInfoResult data =
            questionRecordInfoResultFromJson(response.bodyString);
        if (data.result != null) {
          this._assessmentQuestionRecordInfo.value =
              data.result as QuestionRecordInfo;
          change(this._assessmentQuestionRecordInfo,
              status: RxStatus.success());
        }
      }
    } catch (error) {
      change(null, status: RxStatus.error());
      Log.debug(error);
    } finally {
      EasyLoading.dismiss();
    }
  }

  Future<QuestionRecordInfo?> fetchQuestionRecordInfoDetails(
      String recordId) async {
    var quickreviewRecords = QuestionRecordInfo();
    try {
      EasyLoading.show();
      var response =
          await _assessmentServiceProvider.getAssessmentRecordDetails(recordId);
      if (response.statusCode == 200) {
        QuestionRecordInfoResult data =
            questionRecordInfoResultFromJson(response.bodyString);
        if (data.result != null) {
          quickreviewRecords = data.result as QuestionRecordInfo;
          questionRecordInfo = quickreviewRecords;
        }
      }
    } catch (error) {
      Log.debug(error);
    } finally {
      EasyLoading.dismiss();
    }
    return quickreviewRecords;
  }

  Future<QuestionRecordInfo?> getQuickReviewQuestionGroupByBookCode(
      String bookCode) async {
    EasyLoading.show();
    var quickreviewRecords = QuestionRecordInfo();
    try {
      //var _language = box.get('UserLanguage') ?? 'Simplified';
      // //var _lang = box.get('UserLang') ?? 'Mandarin';
      // ai 语音不支持粤语，文字只能是简体
      var response = await _assessmentServiceProvider
          .getQuickReviewQuestionGroupByBookCode(bookCode, true, true);
      if (response.statusCode == 200) {
        QuestionRecordInfoResult data =
            questionRecordInfoResultFromJson(response.bodyString);
        if (data.result != null) {
          quickreviewRecords = data.result as QuestionRecordInfo;
          questionRecordInfo = quickreviewRecords;
        }
      }
    } catch (error) {
      Log.debug(error);
    } finally {
      EasyLoading.dismiss();
    }
    return quickreviewRecords;
  }

  Future<List<QuestionRecordSection>?> getGrammarGroupQuestionByBookCode(
      String bookCode) async {
    EasyLoading.show();
    var data = KnowledgeDetailsResult();
    List<QuestionRecordSection>? grammars = [];
    try {
      var _language = box.get('UserLanguage') ?? 'Simplified';
      var _lang = box.get('UserLang') ?? 'Mandarin';
      var response = await _assessmentServiceProvider
          .getGramamrQuestionGroupByBookCode(bookCode, _language, _lang);
      if (response.statusCode == 200) {
        data = knowledgeItemsResultFromJson(response.bodyString);
        grammars = data.result!.grammar;
        grammarRecordInfo = grammars;
      }
    } catch (error) {
      print(error);
    } finally {
      EasyLoading.dismiss();
    }
    return grammars;
  }

  Future<void> fetchAssessmentRecordGrading(String recordId) async {
    try {
      var response =
          await _assessmentServiceProvider.getAssessmentGrade(recordId);
      if (response.statusCode == 200) {
        AssessmentRecordsGradesResult data =
            AssessmentRecordsGradesResult.fromJson(
                json.decode(response.bodyString));
        if (data.result != null)
          this._assessmentRecordsGrades.value =
              data.result as AssessmentRecordsGrades;
      }
    } catch (error) {
      Log.debug(error);
    }
  }

  void submitAssessmentRecordGrading(AssessmentGradingDto dto) async {
    try {
      String dtoJson = assessmentGradingDtoToJson(dto);
      var response =
          await _assessmentServiceProvider.submitAssessmentGrade(dtoJson);
      if (response.statusCode == 200) {}
    } catch (error) {
      Log.debug(error);
    }
  }

  void checkBookAssignmentStatus(String classId, List<String> bookIds) async {
    try {
      var response =
          await _bookServiceProvider.checkIfBookAssigned(classId, bookIds);
      if (response.statusCode == 200) {
        var data = bookAssignedFromJson(response.bodyString);
        this._assessmentBenchmarkTests.forEach((bookItem) {
          var index =
              data.indexWhere((element) => element.bookId == bookItem.bookId);
          if (index != -1) {
            bookItem.ifAssigned = data[index].ifAssigned ?? false;
          }
        });
        change(this._assessmentBenchmarkTests, status: RxStatus.success());
      }
    } catch (e) {}
  }

  Future<List<BookItem>> fetchAssessmentBenchmarkBooks(
      String? page, String? limit, String? type, String kind) async {
    List<BookItem> items = [];
    try {
      EasyLoading.show();
      var response = await _assessmentServiceProvider.getAssessmentBooks(
          limit, page, type, kind);
      if (response.statusCode == 200) {
        AssessmentBooksResult data =
            AssessmentBooksResult.fromJson(json.decode(response.bodyString));
        var _language = box.get('UserLanguage') ?? 'Simplified';
        List<String> bookIds = [];
        if (data.list != null && data.list!.length > 0) {
          for (int i = 0; i < data.list!.length; i++) {
            BookItem item = new BookItem();
            //使用contentlink来保存question group id; 使用bookcode来保存assessment type
            item.bookContentLink = data.list![i].id;
            item.bookCode = data.list![i].type;
            item.bookId = data.list![i].bookId;
            //item.bookTitle = data.list![i].title;
            //item.description = data.list![i].description;
            //item.bookImageLink = data.list![i].image;
            item.simBookImageLink = data.list![i].image ?? '';
            // final box = Hive.box('appconfig');
            // var _language = box.get('UserLanguage') ?? 'Simplified';
            if (_language == 'Traditional') {
              item.bookTitle = data.list![i].titleTraditional ?? '';
              item.description = data.list![i].descriptionTraditional ?? '';
              if (item.simBookImageLink != null && item.simBookImageLink != '')
                item.bookImageLink = StrUtil.insertCharAt(
                    item.simBookImageLink!,
                    item.simBookImageLink!.length - 4,
                    "t");
              // Log.debug(insertCharAt(item.simBookImageLink!,
              //     item.simBookImageLink!.length - 4, "t"));
            } else {
              item.bookTitle = data.list![i].title ?? '';
              item.description = data.list![i].description ?? '';
              item.bookImageLink = item.simBookImageLink ?? '';
            }
            item.bookLevel = data.list![i].level.toString();
            item.color = Constants.bookLevelColors
                    .where((element) => element.level == data.list![i].level)
                    .first
                    .color ??
                '#808080';
            items.add(item);
            bookIds.add(item.bookId.toString());
          }
          // var _classId = box.get(CacheManagerKey['currentclass'].toString());
          // checkBookAssignmentStatus(_classId, bookIds);

          _assessmentBenchmarkTests.assignAll(items);
        }
        //if (_assessmentBenchmarkTests.length > 0)
        change(_assessmentBenchmarkTests, status: RxStatus.success());
        // else
        //   change(null, status: RxStatus.empty());
      } else {
        change(null, status: RxStatus.error('Oops, something wrong ...'.tr));
      }
    } catch (error) {
      change(null, status: RxStatus.error('Oops, something wrong ...'.tr));
      Log.debug(error);
    } finally {
      EasyLoading.dismiss();
    }
    return items;
  }

  void fetchAssessmentBooks(
      String? page, String? limit, String? type, String kind) async {
    try {
      var response = await _assessmentServiceProvider.getAssessmentBooks(
          limit, page, type, kind);
      if (response.statusCode == 200) {
        AssessmentBooksResult data =
            AssessmentBooksResult.fromJson(json.decode(response.bodyString));
        var _language = box.get('UserLanguage') ?? 'Simplified';
        if (data.list != null && data.list!.length > 0) {
          List<BookItem> items = [];
          for (int i = 0; i < data.list!.length; i++) {
            BookItem item = new BookItem();
            //使用contentlink来保存question group id; 使用bookcode来保存assessment type
            item.bookContentLink = data.list![i].id;
            item.bookCode = data.list![i].type;
            item.bookId = data.list![i].bookId;
            //item.bookTitle = data.list![i].title;
            //item.description = data.list![i].description;
            //item.bookImageLink = data.list![i].image;
            item.simBookImageLink = data.list![i].image ?? '';
            if (_language == 'Traditional') {
              item.bookTitle = data.list![i].titleTraditional ?? '';
              item.description = data.list![i].descriptionTraditional ?? '';

              if (item.simBookImageLink != null && item.simBookImageLink != '')
                item.bookImageLink = StrUtil.insertCharAt(
                        item.simBookImageLink!,
                        item.simBookImageLink!.length - 4,
                        "t")
                    .replaceAll('.gif', '.jpg');
              // Log.debug(insertCharAt(item.simBookImageLink!,
              //     item.simBookImageLink!.length - 4, "t"));
            } else {
              item.bookTitle = data.list![i].title ?? '';
              item.description = data.list![i].description ?? '';
              item.bookImageLink = item.simBookImageLink ?? '';
            }
            item.bookLevel = data.list![i].level.toString();
            item.color = Constants.bookLevelColors
                    .where((element) => element.level == data.list![i].level)
                    .first
                    .color ??
                '#808080';
            items.add(item);
          }
          _assessmentBooks.assignAll(items);
        }
        //if (_assessmentBooks.length > 0)
        change(_assessmentBooks, status: RxStatus.success());
        // else
        //   change(null, status: RxStatus.empty());
      } else {
        change(null, status: RxStatus.error('Oops, something wrong ...'.tr));
      }
    } catch (error) {
      change(null, status: RxStatus.error('Oops, something wrong ...'.tr));
      Log.debug(error);
    }
  }

  Future<dynamic> fetchAssessmentQuizbookRecords(
      String? limit, String? page, String? type) async {
    var _questionRecords = <QuestionRecord>[];
    try {
      EasyLoading.show();
      var response =
          await _assessmentServiceProvider.getQuizBooks(limit, page, type);
      if (response.statusCode == 200) {
        var data = assessmentRecordsResultFromJson(response.bodyString);
        _questionRecords = data.list as List<QuestionRecord>;
        if (_questionRecords.length > 0) {
          _questionRecords.sort((a, b) {
            var end1 = a.committedTime as int;
            var end2 = b.committedTime as int;
            return end2.compareTo(end1);
          });
        }
      } else {
        Log.debug(response.body);
      }
    } catch (error) {
      Log.debug(error);
    } finally {
      EasyLoading.dismiss();
    }
    return _questionRecords;
  }

  void setCurrentAssessmenbBookType(AssessmentBookType type) {
    this._currentAssessmentBookType.value = type;
  }

  AssessmentBookType getCurrentAssessmentBookType() {
    if (this._currentAssessmentBookType.value.assessmentType == null)
      this._currentAssessmentBookType.value = Constants.assessmentBookTypes[0];
    return this._currentAssessmentBookType.value;
  }

  void clearSelectedBenchmarkBookItems() async {
    this._selectedAssessmentBenchmarkTests.clear();
  }

  void addToSelectedBenchmarkBookItems(
      BookItem book, NanhaiBookReadingTypes readingType) {
    if (readingType == NanhaiBookReadingTypes.assessment) {
      this._selectedAssessmentBenchmarkTests.clear();
      this._selectedAssessmentBenchmarkTests.add(book);

      this._assessmentBenchmarkTests.forEach((book) {
        book.selected = false;
      });

      var bk = this
          ._assessmentBenchmarkTests
          .where((element) => element.bookId == book.bookId)
          .first;
      if (bk.bookId != null) {
        bk.selected = true;
        if (_assessmentBenchmarkTests.length > 0)
          change(_assessmentBenchmarkTests, status: RxStatus.success());
        else
          change(null, status: RxStatus.empty());
      }
    }
  }

  void removeFromSelectedBenchmarkBookItems(
      BookItem book, NanhaiBookReadingTypes readingType) {
    if (readingType == NanhaiBookReadingTypes.assessment) {
      if (this
          ._selectedAssessmentBenchmarkTests
          .where((element) => element.bookId == book.bookId)
          .isNotEmpty) this._selectedAssessmentBenchmarkTests.remove(book);
      var bk = this
          ._assessmentBenchmarkTests
          .where((element) => element.bookId == book.bookId)
          .first;
      if (bk.bookId != null) {
        bk.selected = false;

        if (_assessmentBenchmarkTests.length > 0)
          change(_assessmentBenchmarkTests, status: RxStatus.success());
        else
          change(null, status: RxStatus.empty());
      }
    }
  }

  void fetchStudentAssessmentRecords(
      String classId, AssessmentStudentQueryDto dto) async {
    try {
      EasyLoading.show();
      var response = await _schoolServiceProvider.getStudentAssessmentRecords(
          classId, dto);
      if (response.statusCode == 200) {
        var data = assessmentStudentRecordsResultFromJson(response.bodyString);
        this._studentAssessmentRecord.value = data;
      }
      change(_studentAssessmentRecord, status: RxStatus.success());
    } catch (error) {
      Log.debug(error);
      change(_studentAssessmentRecord, status: RxStatus.empty());
    } finally {
      EasyLoading.dismiss();
    }
  }

  Future<List<AssessmentItem>> fetchStudentAssessments() async {
    List<AssessmentItem> items = [];
    try {
      EasyLoading.show();
      Map<String, dynamic> param = {};
      param['limit'] = 1000;
      param['status'] = ["NEW", "UNDONE"];
      //param['type'] = ["BENCHMARK_TEST"];
      param['page'] = 0;
      param['sortField'] = 'endTime';
      var response = await _assessmentServiceProvider.getMineAssessment(param);
      if (response.statusCode == 200) {
        StudentAssessments data =
            StudentAssessments.fromJson(json.decode(response.bodyString));

        for (int i = 0; i < data.list!.length; i++) {
          AssessmentItem item = AssessmentItem();
          var dt = data.list?[i].endTime ?? 0;
          item.assessmentId = data.list?[i].id ?? '';
          item.audioType = data.list?[i].audioType ?? '';
          item.name = data.list?[i].name ?? '';
          item.instructions = data.list?[i].instruction ?? '';
          item.textType = data.list?[i].textType ?? '';
          item.type = data.list?[i].type ?? '';
          item.classId = data.list?[i].classId ?? '';
          item.className = data.list?[i].className ?? '';
          item.questionGroup = data.list![i].questionGroup ?? null;
          if (dt > 0) {
            item.dueDate = DateTime.fromMillisecondsSinceEpoch(dt);
          }
          item.status = data.list?[i].status ?? '';
          items.add(item);
        }
        Log.debug(items.length);
        _assessItems.assignAll(items);

        if (_assessItems.length > 0)
          change(_assessItems, status: RxStatus.success());
        else
          change(null, status: RxStatus.empty());
      } else {
        change(null, status: RxStatus.error('Oops, something wrong ...'.tr));
      }
    } catch (error) {
      change(null, status: RxStatus.error('Oops, something wrong ...'.tr));
      Log.debug(error);
    } finally {
      EasyLoading.dismiss();
    }
    return items;
  }

  Future<StatusMessageResult> deleteAssessmentByAssessmentId(
      String assessmentId) async {
    var _statusMessageResult = StatusMessageResult();
    try {
      EasyLoading.show();
      var response =
          await _assessmentServiceProvider.deleteAssessmentById(assessmentId);
      if (response.statusCode == 200) {
        _statusMessageResult.status = 1000;
        _assessItems
            .removeWhere((element) => element.assessmentId == assessmentId);
        if (_assessItems.length > 0)
          change(_assessItems, status: RxStatus.success());
        else
          change(null, status: RxStatus.empty());
      } else {
        _statusMessageResult.status = 0;
        change(null, status: RxStatus.error('Oops, something wrong ...'.tr));
      }
    } catch (error) {
      _statusMessageResult.status = 0;
      change(null, status: RxStatus.error('Oops, something wrong ...'.tr));
      Log.debug(error);
    } finally {
      EasyLoading.dismiss();
    }
    return _statusMessageResult;
  }

  void fetchTeacherAssessmentRecordsByClass(
      String classId, String limit, String page) async {
    try {
      var response = await _assessmentServiceProvider.getAssessmentRecords(
          classId, limit, page);
      if (response.statusCode == 200) {
        var data = assessmentRecordsResultFromJson(response.bodyString);
        _assessmentRecords.assignAll(data.list as List<QuestionRecord>);
        if (_assessmentRecords.length > 0)
          change(_assessmentRecords, status: RxStatus.success());
        else
          change(null, status: RxStatus.empty());
      } else {
        change(null, status: RxStatus.error('Oops, something wrong ...'.tr));
      }
    } catch (error) {
      change(null, status: RxStatus.error('Oops, something wrong ...'.tr));
      Log.debug(error);
    }
  }

  void fetchAssessmentsByClass(String classId, AssessmentQueryDto dto) async {
    try {
      EasyLoading.show();
      var response = await _assessmentServiceProvider.getAllAssessmentsByClass(
          classId, dto);
      if (response.statusCode == 200) {
        var data = teacherAssessmentsResultFromJson(response.bodyString);

        // if (data.list != null && data.list!.length > 0) {
        //   data.list!.removeWhere((element) => element.type == 'BENCHMARK_TEST');
        // }
        _assessAllItems.assignAll(data.list ?? []);
        List<AssessmentItem> items = [];
        for (int i = 0; i < data.list!.length; i++) {
          AssessmentItem item = AssessmentItem();
          var duedate = data.list![i].endTime ?? 0;
          var startdate = data.list![i].startTime ?? 0;
          var commitdate = data.list![i].commitTime ?? 0;
          item.assessmentId = data.list![i].id ?? '';
          item.audioType = data.list![i].audioType ?? '';
          item.name = data.list![i].name ?? '';
          item.questionGroup = data.list![i].questionGroup ?? null;
          item.instructions = data.list![i].instruction ?? '';
          item.textType = data.list![i].textType ?? '';
          item.type = data.list![i].type ?? '';
          item.classId = classId;
          if (duedate > 0)
            item.dueDate = DateTime.fromMillisecondsSinceEpoch(duedate);
          item.status = data.list![i].status ?? '';
          if (commitdate > 0)
            item.commitDate = DateTime.fromMillisecondsSinceEpoch(commitdate);
          if (startdate > 0)
            item.startDate = DateTime.fromMillisecondsSinceEpoch(startdate);
          item.mode = data.list![i].mode ?? '';
          item.students = data.list![i].students;
          if (items
                  .where((element) => element.assessmentId == item.assessmentId)
                  .length ==
              0) items.add(item);
        }
        items.sort((a, b) {
          var end1 = a.startDate as DateTime;
          var end2 = b.startDate as DateTime;
          return end2.compareTo(end1);
        });

        _assessItemsForTeacher.assignAll(items);
        if (_assessItemsForTeacher.length > 0)
          change(_assessItemsForTeacher, status: RxStatus.success());
        else
          change(null, status: RxStatus.empty());
      } else {
        change(null, status: RxStatus.error('Oops, something wrong ...'.tr));
      }
    } catch (error) {
      change(null, status: RxStatus.error('Oops, something wrong ...'.tr));
      Log.debug(error);
    } finally {
      EasyLoading.dismiss();
    }
  }
}
